import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

public class Solution2 {
    HashMap<Integer, List<Integer>> maps;
    int[] nums;
    Random random;
    public Solution2(int[] nums) {
        this.nums = nums;
        random = new Random();
        maps = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            List<Integer> list = maps.getOrDefault(nums[i], new ArrayList<>());
            list.add(i);
            maps.put(nums[i], list);
        }
    }

    public int pick1(int target) {
        List<Integer> list = maps.get(target);
        return list.get((int) (Math.random() * list.size()));
    }

    //水塘抽样
    public int pick(int target) {
        int res = 0;
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                ++count;
                if (random.nextInt(count) == 0) res = i;
            }
        }
        return res;
    }
}
